from django.core import serializers
from django.db.models import Q, Case, When
from django.db import models
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import ApiGroupWorkflow
from rest_framework.views import APIView

class FlowTest(APIView):

    @csrf_exempt
    def get(self, request):
        user_id = request.query_params.get('user_id')
        robot_id = request.query_params.get('robot_id')
        group_id = request.query_params.get('group_id')
        db = ApiGroupWorkflow.objects.annotate(
            has_group_id=Case(
                When(group_id='', then=False),  # group_id 为空值时，认为没有 name 值
                When(group_id__isnull=True, then=False),  # group_id 为 NULL 时，认为没有 name 值
                default=True,  # 其它情况都认为有 name 值
                output_field=models.BooleanField(),
            ),
        ).filter(
            Q(robot_id=robot_id) & Q(user_id=user_id) & (Q(group_id=group_id) if group_id else Q(has_group_id=False))
        )
        workflow_id = db.values_list('workflow_id', flat=True)
        workflow_title = db.values_list('workflow_title', flat=True)
        workflow_content = db.values_list('workflow_content', flat=True)
        status = db.values_list('status', flat=True)
        workflow_id = list(workflow_id)
        workflow_title = list(workflow_title)
        workflow_content = list(workflow_content)
        status = list(status)
        return JsonResponse({
            "code": 200,
            'user_id':user_id,
            'robot_id':robot_id,
            'group_id': group_id,
            'workflow_id':workflow_id,
            'workflow_title':workflow_title,
            'workflow_content':workflow_content,
            'status ':status
        })

    @csrf_exempt
    def post(self, request):
        user_id = request.data.get('user_id')
        workflow_id = request.data.get('workflow_id')
        robot_id = request.data.get('robot_id')
        workflow_title = request.data.get('workflow_title')
        group_id = request.data.get('group_id')
        workflow_content = request.data.get('workflow_content')
        im_flow = ApiGroupWorkflow(
            user_id=user_id,
            workflow_id=workflow_id,
            robot_id=robot_id,
            group_id=group_id,
            workflow_content=workflow_content,
            workflow_title=workflow_title
        )
        im_flow.save()
        return JsonResponse({
            "code": 200,
        })



